package jsu.xnm.evelyn.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import jsu.xnm.evelyn.bean.Category;
import jsu.xnm.evelyn.bean.Dish;
import jsu.xnm.evelyn.dto.DishDto;
import jsu.xnm.evelyn.service.CategoryService;
import jsu.xnm.evelyn.service.DishService;
import jsu.xnm.evelyn.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xnm
 * @version 1.0
 */

/**
 * 同时添加菜品（dish）和菜品口味(dish_flavor)
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Resource
    private DishService dishService;

    @Resource
    private CategoryService categoryService;

    /**
     * 新增菜品(dish + dish_flavor)
     * @param dishDto
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody DishDto dishDto){
        //没有重写toString方法，所以打印出来的没有其父类的各个属性，但实际上已经封装了（可断点调试）
        log.info("dishDto:{}",dishDto);
        dishService.saveDishAndFlavor(dishDto);
        return Result.success("新增菜品成功!");
    }

    /**
     * 多表分页查询
     * @param pageNo
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result page(@RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                       @RequestParam(value = "name",defaultValue = "") String name){
        //1.获取到菜品的原始信息
        LambdaQueryWrapper<Dish> queryWrapper = Wrappers.lambdaQuery();
        if(StringUtils.hasText(name)){
            queryWrapper.like(Dish::getName,name);
        }
        Page<Dish> dishPage = dishService.page(new Page<>(pageNo, pageSize), queryWrapper);

        /*将上面获取的数据拷贝到dtoPage*/
        //2.同时也要获取到该菜品关联category_id获取的该菜品类型的名称
        //因为DishDto是Dish的子类，所有DishDto有Dish的所有属性，而DishDto也有新增的categoryName属性
        //所以这里需要将dishPage转换为dtoPage,然后返回dtoPage
        Page<DishDto> dtoPage = new Page<>();
        //拷贝分页的相关属性（忽略获取到的records集合,单独处理）
        /**
         * 比如
         *     private long total;
         *     private long size;
         *     private long current;
         *     private List<OrderItem> orders;
         *     private boolean optimizeCountSql;
         *     private boolean searchCount;
         *     private boolean optimizeJoinOfCountSql;
         *     private Long maxLimit;
         *     private String countId;
         */
        BeanUtils.copyProperties(dishPage,dtoPage, "records");

        //3.遍历records的每条记录，完成categoryName属性封装=>[得到一个新的records]
        List<DishDto> dtoList = dishPage.getRecords().stream().map(dish ->{
            //将每个dish的基础属性赋值到dishDto中
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);//拷贝基础属性(dish->dishDto)

            //查询分类名称
            Category category = categoryService.getById(dish.getCategoryId());
            if(category != null){
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());//将dishDto收集成一个集合

        // 4. 设置转换后的记录
        dtoPage.setRecords(dtoList);
        return Result.success(dtoPage);
    }

    /**
     * 根据id查询菜品信息和口味信息(多表查询)
     * @param id
     * @return
     */
    @GetMapping("/getDishAndFlavorById/{id}")
    public Result getDishAndFlavorById(@PathVariable("id") Long id){
        DishDto dishAndFlavorById = dishService.getDishAndFlavorById(id);
        return Result.success(dishAndFlavorById);
    }

    @PutMapping("/update")
    public Result update(@RequestBody DishDto dishDto){
        dishService.updateDishAndFlavor(dishDto);
        return Result.success("修改菜品成功!");
    }
}
